package com.streambolics.android;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;

import com.streambolics.std.BeanSainParser;

/**
 * The base class for all Streambolics activities.
 * 
 * The StandardActivity provides the tools needed to support error resistant
 * applications that do not exit with no useful error message.
 * 
 * @author Sauron
 * 
 */
public class StandardActivity extends Activity
{
    private int    _MenuId;
    private Bundle _CreationBundle;

    public void displayError (String aAction, String aError)
    {
        new AlertDialog.Builder (this).setTitle (aAction).setMessage (aError).setNeutralButton ("OK", new DialogInterface.OnClickListener ()
        {
            @Override
            public void onClick (DialogInterface dialog, int which)
            {
                // TODO : exit the application ???
            }
        }).show ();
    }

    public void displayException (String aAction, Exception e)
    {
        displayError (aAction, e.getMessage ());
    }

    protected void loadFromBundle (Bundle aData)
    {
        if (aData == null)
        {
            return;
        }

        String s = aData.getString ("SerializedObject");
        if (s != null)
        {
            loadFromSain (s);
            return;
        }
        long id = aData.getLong ("ObjectId");
        if (id != 0)
        {
            loadFromId (id);
            return;
        }
    }

    protected void loadFromId (long id)
    {
        // TODO : create the appropriate query and send it through an
        // AsyncDownloader.
    }

    protected void loadFromSain (String aSain)
    {
        new BeanSainParser (this).parseLines (aSain);
    }

    @Override
    protected void onCreate (Bundle savedInstanceState)
    {
        super.onCreate (savedInstanceState);
        _CreationBundle = savedInstanceState;
    }

    @Override
    public boolean onCreateOptionsMenu (Menu menu)
    {
        if (_MenuId != 0)
        {
            getMenuInflater ().inflate (_MenuId, menu);
            return true;
        }
        else
        {
            return super.onCreateOptionsMenu (menu);
        }
    }

    @Override
    protected void onStart ()
    {
        super.onStart ();
        if (_CreationBundle != null)
        {
            try
            {
                loadFromBundle (_CreationBundle);
            }
            finally
            {
                _CreationBundle = null;
            }
        }

    }

    protected void setMenu (int aMenuId)
    {
        _MenuId = aMenuId;
    }

}
